package com.example.assignment4.service;

import com.example.assignment4.entity.Commodity;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author guanruwang
 * @date 2023/10/11$
 */

@Service
public class CommodityService {

    // 创建线程安全的Map，模拟Todo信息的存储
    private Map<Long, Commodity> commodities =
            Collections.synchronizedMap(new HashMap<Long, Commodity>());

    public Commodity addCommodity(Commodity commodity) {
        commodities.put(commodity.getId(), commodity);
        return commodity;
    }

    public Commodity getCommodity(long id) {
        return commodities.get(id);
    }

    public List<Commodity> findCommodities(String name, String description) {
        List<Commodity> result = new ArrayList<>();
        for (Commodity commodity : commodities.values()) {
            if (name != null && !commodity.getName().contains(name)) {
                continue;
            }
            if (description != null && !description.equals(commodity.getDescription())) {
                continue;
            }
            result.add(commodity);
        }
        return result;
    }

    public void updateCommodity(long id, Commodity commodity) {
        Commodity commodity2 = commodities.get(id);
        commodity2.setName(commodity.getName());
        commodity2.setDescription(commodity.getDescription());
        commodities.put(id, commodity2);
    }

    public void deleteCommodity(long id) {
        commodities.remove(id);
    }
}
